using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using MonoTouch.Foundation;
using MonoTouch.UIKit;
using CoachingOrganizer.iOS.Controllers.Tools.EmotionsPack;
using CoachingOrganizer.Logic.Models.Tools.EmotionsPack;

namespace CoachingOrganizer.iOS.DataSources.Tools.EmotionsPack
{
    public class EmotionsPackDataSource : UITableViewSource
    {
        public const string CellIdentifer = "GoalCell";

        private readonly UITableView _view;
        private readonly ChooseEmotionsPackDetailsViewController _controller;
        private readonly EmotionsPackModel _model;
        private readonly Dictionary<string, string[]> _emotionNames;
        private readonly Lazy<NSString> _platformCellIdentifer = new Lazy<NSString>(() => new NSString(CellIdentifer));

        public EmotionsPackDataSource(UITableView view, ChooseEmotionsPackDetailsViewController controller, EmotionsPackModel model)
        {
            _view = view;
            _controller = controller;
            _model = model;
            _emotionNames = GetEmotionNames();
            _view.RegisterClassForCellReuse(typeof(UITableView), _platformCellIdentifer.Value);
        }

        public override UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath)
        {
            UITableViewCell cell = _view.DequeueReusableCell(_platformCellIdentifer.Value, indexPath);
            cell.TextLabel.Text = _emotionNames.Values.ElementAt(indexPath.Section)[indexPath.Row];
            return cell;
        }

        public override string TitleForHeader(UITableView tableView, int section)
        {
            return _emotionNames.Keys.ElementAt(section);
        }

        public override int RowsInSection(UITableView tableview, int section)
        {
            return _emotionNames.Values.ElementAt(section).Length;
        }

        public override int NumberOfSections(UITableView tableView)
        {
            return _emotionNames.Count;
        }

        private Dictionary<string, string[]> GetEmotionNames()
        {
            Dictionary<string, string[]> outResult = new Dictionary<string, string[]>();
            string plistFilePath = NSBundle.MainBundle.PathForResource("EmotionNames", "plist");
            using (NSDictionary dataDictionary = NSDictionary.FromFile(plistFilePath))
                foreach (KeyValuePair<NSObject, NSObject> item in dataDictionary)
                {
                    string key = (NSString)item.Key;
                    string[] items = NSArray.FromArray<NSString>((NSArray)item.Value).Cast<string>().ToArray();
                    outResult.Add(key, items);
                }
            return outResult;
        }
    }
}